<template>
  <!-- 富文本组件 -->
  <TinymceEditor
    v-if="show"
    ref="editorRef"
    :key="tinymceId"
    :id="tinymceId"
    :init="editorInit"
    v-model="value"
    @input="value = $event"
  />
</template>

<script lang="ts" setup>
import { computed, ref, nextTick } from "vue";
import { Editor, RawEditorSettings } from "tinymce/tinymce";
import TinymceEditor from "@tinymce/tinymce-vue";

import tinymceConfig from "./config";

// -------------------------- 页面参数 --------------------------
const props = defineProps<{
  modelValue: string;
}>();

const $emits = defineEmits<{
  'update:modelValue': [string],
  blur: []
}>();

const value = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    $emits('update:modelValue', value);
  }
});

const editorRef = ref<Editor>();

// -------------------------- 页面数据 --------------------------
const tinymceId = ref((Date.now() + Math.round(Math.random() * 1000)).toString());

// -------------------------- 初始化配置 --------------------------
const editorInit = ref<RawEditorSettings>({
  ...tinymceConfig,

  id: tinymceId.value,

  language: "zh_CN",

  setup: (editor) => {
    // 初始化编辑器
    editor.on("init", () => {
      // 初始化编辑器默认字体大小
      // editor.getBody().style.fontSize = "10pt";
      // 阻止富文本框中默认的ctrl+s/Command+s事件，会造成页面刷新
      editor.getBody().addEventListener("keydown", (e) => {
        if ((e.ctrlKey || e.metaKey) && e.key === "s") {
          e.preventDefault();
        }
      }, true);
      editor.getDoc().addEventListener("click", (e) => {
        document.body.click();
      });
    });

    // 失去焦点
    editor.on("blur", () => {
      $emits('blur');
    });

  },
});

const show = ref(false);
nextTick(() => {
  show.value = true;
});
</script>
